﻿using GameFramework;
using System;
using System.Collections.Generic;
using System.IO;
using UnityGameFramework.Runtime;

namespace ProjectMG
{
    public static class ConfigExtension
    {
        private static readonly Dictionary<string, bool> s_ConfigLoadedFlags = new Dictionary<string, bool>();

        public static bool IsAllConfigsLoaded(this ConfigComponent configComponent)
        {
            if (s_ConfigLoadedFlags.Count <= 0)
            {
                return false;
            }

            foreach (KeyValuePair<string, bool> configLoadedFlag in s_ConfigLoadedFlags)
            {
                if (!configLoadedFlag.Value)
                {
                    return false;
                }
            }

            return true;
        }

        public static void SetConfigLoadedFlag(this ConfigComponent configComponent, string configName)
        {
            if (s_ConfigLoadedFlags.ContainsKey(configName))
            {
                s_ConfigLoadedFlags[configName] = true;
            }
            else
            {
                Log.Warning("Not load config '{0}' yet.", configName);
            }
        }

        public static void LoadConfigs(this ConfigComponent configComponent)
        {
            s_ConfigLoadedFlags.Clear();
            if (GameEntry.BuiltinData.UseConfigBytes)
            {
                string assetName = AssetUtility.GetBinaryConfigAsset();
                s_ConfigLoadedFlags.Add(assetName, false);
                GameEntry.Config.ReadData(assetName, Constant.AssetPriority.ConfigAsset);
            }
            else if (GameEntry.Base.EditorResourceMode)
            {
                string configListAssetName = GameEntry.Resource.GetBinaryPath(AssetUtility.GetConfigListAsset());
                string[] configNames = Utility.Converter.GetString(File.ReadAllBytes(configListAssetName)).Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string configName in configNames)
                {
                    LoadConfig(configName);
                }
            }
            else
            {
                Log.Error("Read config from file is not support without editor resource mode.");
            }
        }

        private static void LoadConfig(string configName)
        {
            if (string.IsNullOrEmpty(configName))
            {
                Log.Warning("Config name is invalid.");
                return;
            }

            string assetName = AssetUtility.GetConfigAsset(configName);
            s_ConfigLoadedFlags.Add(assetName, false);
            GameEntry.Config.ReadData(assetName, Constant.AssetPriority.ConfigAsset);
        }
    }
}
